package demo.miner;

import java.util.ArrayList;
import java.util.List;

import jtech.math.Vec2f;

public class GroupMove {
	
	private static final int STATE_NO_SEARCH = 0;
	private static final int STATE_NO_FOUND  = 1;
	private static final int STATE_FOUND     = 2;
	
	private Game game;

	private Vec2f target;
	private EntityUnit leader;
	private List<EntityUnit> group;

	private Path path;
	private int state;

	public GroupMove(Game game, Vec2f target, List<EntityUnit> selectedUnits) {
		this.game = game;
		this.target = target;
		group = new ArrayList<EntityUnit>(selectedUnits);
		float minDist = Float.MAX_VALUE;
		for (EntityUnit unit : selectedUnits) {
			float dist = unit.getPosition().distanceSq(target);
			if (dist < minDist) {
				minDist = dist;
				leader = unit;
			}
		}
		group.remove(leader);
		searchPath();		
	}
	
	public boolean searchPath() {
		if (state == STATE_NO_SEARCH || game.isRebuildMapPassableGrid()) {
			List<Vec2f> waypoints = null;// game.searchPath(leader.getPosition(), target);
			if (waypoints.size() == 0) {
				state = STATE_NO_FOUND;
				return false;
			}
			if (waypoints.size() > 1) {
				waypoints.remove(0);
			}
			path = new Path(waypoints);
			state = STATE_FOUND;
		}
		return (state == STATE_FOUND);
	}

	public Vec2f getTarget() {
		return target;
	}

	public EntityUnit getLeader() {
		return leader;
	}

	public List<EntityUnit> getGroup() {
		return group;
	}

	public Path getPath() {
		return path;
	}

	public boolean isFoundPath() {
		return (state == STATE_FOUND);
	}
	
	public int getGroupSize() {
		return group.size();
	}
	
	public boolean isLeader(EntityUnit unit) {
		return unit.getId() == leader.getId();
	}
	
}
